// pages/goods_detail/main.js
import { request } from "../../request/index.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj:{},
    // 商品是否被收藏过
    isCollect:false
  },
// 商品对象
GoodsInfo:{},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    let pages =  getCurrentPages();
    let currentPage=pages[pages.length-1];
    let options=currentPage.options;

    const {goods_id}=options;
    // console.log(goods_id);
    this.getGoodsDetail(goods_id);


      
  },
  async getGoodsDetail(goods_id){
    const goodsObj= await request({url:"/goods/detail",data:{goods_id}});
    this.GoodsInfo=goodsObj.data.message;
        // 获取缓存中的商品收藏的数组
        let collect=wx.getStorageSync("collect")||[];
        // 判断当前商品是否被收藏了
        let isCollect=collect.some(v=>v.goods_id===this.GoodsInfo.goods_id);
    // console.log(res);
    this.setData({
      goodsObj:{
        goods_name:goodsObj.data.message.goods_name,
        goods_price:goodsObj.data.message.goods_price,
        goods_introduce:goodsObj.data.message.goods_introduce,
        pics:goodsObj.data.message.pics
      },
      isCollect
    })
  },
  // 点击轮播图放大预览
  handlePreviewItem(e){
    // console.log("预览")\
    const urls= this.GoodsInfo.pics.map(v=>v.pics_mid);
    const current=e.currentTarget.dataset.url;
    wx.previewImage({
      current,
      urls
    });
      
  },
  handleCartAdd(){
    // console.log("gwc")
    // 获取缓存中的购物车数组
    let cart = wx.getStorageSync("cart",cart)||[];
    // 判断商品是否存在购物车中
    let index =cart.findIndex(v=>v.goods_id=== this.GoodsInfo.goods_id);
    if(index===-1){
      this.GoodsInfo.num=1;
      this.GoodsInfo.checked=true;
      cart.push(this.GoodsInfo);
    }else{
      cart[index].num++;
    }
      wx.setStorageSync("cart", cart);
      wx.showToast({
        title: '加入购物车成功',
        icon: 'success',
        mask: true
      });
        
        
  },
  // 点击收藏
  handleCollect(){
    let isCollect=false;
    // 1获取缓存中的商品收藏数组
    let collect =wx.getStorageSync("collect")||[];
    // 判断商品是否收藏
    let index=collect.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id);
    // 当index！=-1时，
    if(index!==-1){
      collect.splice(index,1);
      isCollect=false;
      wx.showToast({
        title: '取消收藏成功',
        icon: 'success',
        mask: true
      });
        
    }else{
      collect.push(this.GoodsInfo);
      isCollect=true;
      wx.showToast({
        title: '收藏成功',
        icon: 'success',
        mask: true
      });
    }
    // 4把数组存入缓存中
    wx.setStorageSync("collect", collect);
    this.setData({
      isCollect
    })
      
  }
})